import {
  reqAddOrUpdateCart,
  reqGoodsInfo
} from '../../api/index';
Page({
  data: {
    goodsInfo: {}, //商品信息
    showAction: false, //控制弹窗
    flag: '', //add|buy
    goodsId: '', //存储商品ID
    count: 1, //收集商品的数量
    blessing: '' //祝福语
  },
  //生命周期函数
  onLoad(options) {
    // 存储商品ID
    this.setData({
      goodsId: options.goodsId
    })
    this.getGoodsInfo(options.goodsId);
  },
  //获取商品详情的方法
  async getGoodsInfo(id) {
    const result = await reqGoodsInfo(id);
    if (result.code == 200) {
      this.setData({
        goodsInfo: result.data
      })
    }
  },
  //加入购物车
  addCart() {
    //弹出弹窗
    this.setData({
      showAction: true, //展示弹窗
      flag: 'add'
    })
  },
  //立即购买
  buyNow() {
    this.setData({
      showAction: true,
      flag: 'buy'
    })
  },
  //点击加入购物车确定按钮完成业务
  async addGoods() {
    const {
      goodsId,
      count,
      blessing
    } = this.data;
    // 祝福语不能为空
    if (blessing.trim() == '') {
      wx.showToast({
        title: '祝福语不能为空',
        icon: 'error'
      })
      return;
    }
    // 加入购物车
    await reqAddOrUpdateCart(goodsId, count, blessing);
    // 关闭弹出，清空数据
    this.setData({
      showAction: false,
      flag: '',
      count: 1,
      blessing: ''
    })
  },
  //点击立即购买确定按钮的业务
  buy(){
    const {blessing,goodsId} = this.data;
    if(blessing.trim()==''){
       wx.showToast({
          title:'祝福语必填',
          icon:'error'
       })
       return ;
    }
    //页面跳转到订单页
    wx.navigateTo({
      url: `/pages/order/order?blessing=${blessing}&goodsId=${goodsId}`,
    })
  },
  //弹窗确定按钮
  handler() {
    const token = wx.getStorageSync('TOKEN');
    if (token) {
      if (this.data.flag === 'add') {
        this.addGoods()
      } else {
        this.buy();
      }
    } else {
      //未授权，跳转到登录页
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  // 点击遮罩层，弹窗关闭
  overPlay() {
    this.setData({
      showAction: false,
      flag: ''
    })
  },
  //计步器数值发生变化的回调
  changeCount(event) {
    this.setData({
      count: event.detail
    })
  },

})